package com.js.myapp.system.service;

// Created by JS on 2020/7/18.

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;

import com.js.basicutils.LogUtils;
import com.js.basicutils.NetUtils;
import com.js.basicutils.locate.LocationUtil;
import com.js.myapp.R;
import com.js.myapp.system.activity.MainActivity;

public class LocationService extends Service {

    private static final int CHANNEL_ID = 622;

    private NotificationChannel channel;
    private LocationManager locationManager;
    private Location myLocation = null;
    private int logCount = 0;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        public LocationService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocationService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            showNotify();
        }
        startLocation();
        return START_STICKY;
    }

    private void startLocation() {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false); //无海拔要求   criteria.setBearingRequired(false);//无方位要求
        criteria.setCostAllowed(true);//允许产生资费   criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
        String bestProvider = locationManager.getBestProvider(criteria, false);

        if (NetUtils.isNetworkAvailable(this) && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
        } else {
            LogUtils.d(this, "定位开启失败！");
        }

//        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
//                    && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//                return;
//            }
//            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
//        } else {
//            LogUtils.d(this, "定位开启失败！");
//        }
    }

    private LocationListener locationListener = new LocationListener() {

        // Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        public void onStatusChanged(String provider, int status, Bundle extras) {
            if (status == LocationProvider.OUT_OF_SERVICE || status == LocationProvider.TEMPORARILY_UNAVAILABLE) {

            }
        }

        // Provider被enable时触发此函数，比如GPS被打开
        public void onProviderEnabled(String provider) {

        }

        // Provider被disable时触发此函数，比如GPS被关闭
        public void onProviderDisabled(String provider) {

        }

        // 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        public void onLocationChanged(Location location) {
            if (LocationUtil.isBetterLocation(location, myLocation)) {
                if (myLocation != null) {
                    myLocation = location;
                } else {
                    myLocation = location;
                }
            }
            // 当定位范围在正确的范围内时保存轨迹点
            if (myLocation.getLongitude() > 50 &&
                    myLocation.getLongitude() < 150 &&
                    myLocation.getLatitude() > 0 &&
                    myLocation.getLatitude() < 60) {

                logCount ++;

                // 现在已经定位成功，可以将定位的数据保存下来，这里我新建的一个Const类，保存全局静态变量
//                Const.LONGITUDE = myLocation.getLongitude() + 0.00003487;
//                Const.LATITUDE = myLocation.getLatitude() - 0.00052035;

//                EventBus.getDefault().post(new LocationEvent(myLocation));
                String locusString = myLocation.getLongitude() + " " + myLocation.getLatitude();
				LogUtils.i(this, logCount + "后台服务获取的位置：" + locusString);
            }
        }
    };

    //显示后台定位通知栏（此为8.0版本通知栏）
    private void showNotify() {
        if (channel == null) {
            channel = createNotificationChannel();
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), getPackageName());
        Intent intent = new Intent(this, MainActivity.class);
        builder.setContentIntent(PendingIntent.getActivity(this, 0, intent, 0))
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.icon_app))
                .setSmallIcon(R.mipmap.icon_app)
                .setContentTitle("正在后台定位")
                .setContentText("定位进行中")
                .setOngoing(true)
                .setWhen(System.currentTimeMillis());
        Notification build = builder.build();
        //调用这个方法把服务设置成前台服务
        startForeground(CHANNEL_ID, build);
    }

    @TargetApi(Build.VERSION_CODES.O)
    private NotificationChannel createNotificationChannel() {
        NotificationChannel notificationChannel = new NotificationChannel(getPackageName(), getPackageName(), NotificationManager.IMPORTANCE_HIGH);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
        return notificationChannel;
    }
}
